<script setup lang="ts">
import { dayjs } from 'element-plus'
import { computed, ref, reactive, onMounted } from 'vue'
import { instance } from '@/utils/request'
import { ElMessageBox, ElNotification } from 'element-plus'
import { useStorage } from '@vueuse/core'
import { useLoadingStore } from '@/store/loading'
import { formatSeconds } from '@/utils/time'
import axios from 'axios'

const loc = import.meta.env.VITE_LOC

const { toggleLoading } = useLoadingStore()

const taskStatus = useStorage<any>('task-status', {})

const timeLineItem = computed(() => {
  if (taskStatus.value?.logs) {
    return Object.keys(taskStatus.value?.logs)
      .map((item) => {
        return {
          time: dayjs(item).format('YYYY-MM-DD HH:mm:ss'),
          value: taskStatus.value?.logs[item],
        }
      })
      .reverse()
  } else {
    return []
  }
})

const getTaskName = (val) => {
  const map = {
    1: '取料任务',
    2: '放料任务',
    3: '送往清洗任务',
    4: '清洗返回任务',
    default: '手动任务',
  }
  return map[val] || map.default
}

const getTaskStatus = (val) => {
  const map = { 2: '执行中', 3: '已完成', 4: '异常终止', default: '未知' }
  return map[val] || map.default
}

const getTaskColor = (val) => {
  const map = { 2: 'warning', 3: 'success', 4: 'danger', default: 'danger' }
  return map[val] || map.default
}

const getTaskCarName = (val) => {
  const map = { 1: '1号AGV', 2: '2号AGV', default: '未知' }
  return map[val] || map.default
}

/**
 * 当前时间
 */
const currentTime = ref(dayjs())

/**
 * 运行时间
 */
const runningTime = computed(() => {
  const { startTime, endTime, updateTime, status } = taskStatus.value

  let second =
    status === '2'
      ? currentTime.value.diff(dayjs(startTime), 'seconds')
      : dayjs(endTime || updateTime).diff(dayjs(startTime), 'seconds')

  return `累计用时 ${formatSeconds(second)}`
})

onMounted(() => {
  setInterval(() => {
    currentTime.value = dayjs()
  }, 1000)
})

const formData = ref({
  pattern: 1,
  rid: 1,
  targetWeight: 5,
  type: 1,
})

const formSubmit = async () => {
  await ElMessageBox.confirm('请确认是否开始执行任务', '警告')
  try {
    toggleLoading(true)
    await instance({
      url: `/dc-task/v1/create`,
      method: 'post',
      data: formData.value,
    })
    ElNotification({ type: 'success', title: '开始执行任务' })
    dialogInfo.vislble = false
    toggleLoading(false)
  } catch (error) {
    toggleLoading(false)
  }
}

const dialogInfo = reactive({
  vislble: false,
  title: '',
  width: 600,
})

const dialogOpen = (pattern) => {
  formData.value.type = pattern === 1 ? 1 : 5
  formData.value.pattern = pattern
  dialogInfo.title = pattern === 1 ? '自动任务' : '手动任务'
  dialogInfo.vislble = true
  dialogInfo.width = pattern === 1 ? 500 : 460
}

const ketaiTask = async (code) => {
  await ElMessageBox.confirm('请确认是否开始执行任务', '警告')
  try {
    toggleLoading(true)
    await axios({
      url: `http://192.168.1.10:8080/tabletOrder/distributeOrder/${code}`,
      method: 'get',
    })
    ElNotification({ type: 'success', title: '开始执行任务' })
    dialogInfo.vislble = false
    toggleLoading(false)
  } catch (error) {
    toggleLoading(false)
  }
}

const threeAgvTask = async (id) => {
  await ElMessageBox.confirm('请确认是否开始执行任务', '警告')
  try {
    toggleLoading(true)
    await instance({
      url: `/procedure/v1/3Tagv`,
      method: 'get',
      params: { id },
    })
    ElNotification({ type: 'success', title: '开始执行任务' })
    dialogInfo.vislble = false
    toggleLoading(false)
  } catch (error) {
    toggleLoading(false)
  }
}
</script>

<template>
  <div class="common w-82 h-124 text-#96d8ff">
    <div class="title">任务模块</div>
    <div class="flex flex-col gap-2">
      <div class="font-bold">下发任务</div>
      <div class="mb-1 flex gap-4">
        <div>
          <ElButton color="#4e648763" @click="dialogOpen(1)">自动任务</ElButton>
        </div>
        <div>
          <ElButton color="#4e648763" @click="dialogOpen(2)">手动任务</ElButton>
        </div>
        <ElDropdown v-if="loc === '815'">
          <ElButton color="#4e648763">其他任务</ElButton>
          <template #dropdown>
            <ElDropdownMenu>
              <ElDropdownItem @click="ketaiTask(320898751531)">2T 叉车 - 空区域取货</ElDropdownItem>
              <ElDropdownItem @click="ketaiTask(2827744221718)">2T 叉车 - 空区域卸货</ElDropdownItem>
              <ElDropdownItem @click="ketaiTask(1845415742401)">2T 叉车 - 815取货演示</ElDropdownItem>
              <ElDropdownItem @click="ketaiTask(13410881978957)">2T 叉车 - 休息10 </ElDropdownItem>
              <ElDropdownItem @click="ketaiTask(3601526354829)">2T 叉车 - 左二层取右一层 卸10</ElDropdownItem>
              <ElDropdownItem @click="ketaiTask(13151239422488)">2T 叉车 - 右二层取左一层 卸10</ElDropdownItem>
              <ElDropdownItem @click="ketaiTask(13327929872867)">2T 叉车 - 左一层取右二层 卸10</ElDropdownItem>
              <ElDropdownItem @click="ketaiTask(13380323621819)">2T 叉车 - 右一层取左二层 卸10</ElDropdownItem>
              <ElDropdownItem @click="threeAgvTask(1)" divided>3T AGV - 8152 - 开始任务</ElDropdownItem>
              <ElDropdownItem @click="threeAgvTask(2)">3T AGV - 8152 - 取消任务</ElDropdownItem>
              <ElDropdownItem @click="threeAgvTask(3)">3T AGV - 巡检 - 开始任务</ElDropdownItem>
              <ElDropdownItem @click="threeAgvTask(4)">3T AGV - 巡检 - 取消任务</ElDropdownItem>
              <ElDropdownItem @click="threeAgvTask(5)">3T AGV - 返回 - 开始任务</ElDropdownItem>
              <ElDropdownItem @click="threeAgvTask(6)">3T AGV - 返回 - 取消任务</ElDropdownItem>
            </ElDropdownMenu>
          </template>
        </ElDropdown>
      </div>
      <ElDialog v-model="dialogInfo.vislble" :title="dialogInfo.title" :width="dialogInfo.width" :align-center="true">
        <ElForm label-width="100px" label-suffix="：">
          <ElFormItem label="AGV 小车">
            <ElRadioGroup v-model="formData.rid">
              <ElRadioButton :label="1">1号AGV</ElRadioButton>
              <ElRadioButton :label="2">2号AGV</ElRadioButton>
            </ElRadioGroup>
          </ElFormItem>
          <ElFormItem label="任务类型">
            <ElRadioGroup v-if="formData.pattern === 1" v-model="formData.type">
              <ElRadioButton :label="1">取料任务</ElRadioButton>
              <ElRadioButton :label="2">放料任务</ElRadioButton>
              <ElRadioButton :label="3">送往清洗</ElRadioButton>
              <ElRadioButton :label="4">清洗返回</ElRadioButton>
            </ElRadioGroup>
            <ElSelect class="w-full" v-if="formData.pattern === 2" v-model="formData.type">
              <template v-if="loc === '375'">
                <ElOptionGroup label="充电室">
                  <ElOption :value="5" label="从任意等待点返回充电室" />
                  <ElOption :value="16" label="充电室 => 1344取料等待点" />
                  <ElOption :value="17" label="充电室 => 1108放料等待点" />
                </ElOptionGroup>
                <ElOptionGroup label="取料区">
                  <ElOption :value="6" label="1344取料升降台 => 1344取料等待点（出）" />
                  <ElOption :value="7" label="1344取料等待点 => 1344取料升降台（进）" />
                  <ElOption :value="8" label="1344取料升降台 => 1108放料等待点" />
                </ElOptionGroup>
                <ElOptionGroup label="放料区">
                  <ElOption :value="9" label="1108放料升降台 => 1108放料等待点（出）" />
                  <ElOption :value="10" label="1108放料等待点 => 1108放料升降台（进）" />
                  <ElOption :value="11" label="1108放料升降台 => 1344取料等待点" />
                </ElOptionGroup>
                <ElOptionGroup label="清洗区">
                  <ElOption :value="12" label="1344取料等待点 => 1344清洗区等待点" />
                  <ElOption :value="13" label="1344清洗区 => 1344取料等待点" />
                  <ElOption :value="14" label="1344清洗区 => 1344清洗区等待点（出）" />
                  <ElOption :value="15" label="1344清洗区等待点 => 1344清洗区（进）" />
                </ElOptionGroup>
              </template>
              <template v-if="loc === '815'">
                <ElOption :value="5" label="从任意点返回充电室" />
                <ElOption :value="16" label="充电室 => 等待点" />
                <ElOption :value="6" label="升降台 => 等待点" />
                <ElOption :value="7" label="等待点 => 升降台" />
                <ElOption :value="12" label="等待点 => 清洗等待点" />
                <ElOption :value="13" label="清洗区 => 等待点" />
                <ElOption :value="14" label="清洗区 => 清洗等待点" />
                <ElOption :value="15" label="清洗等待点 => 清洗区" />
              </template>
            </ElSelect>
          </ElFormItem>
          <ElFormItem :label="`${formData.type === 1 ? '取料' : '放料'}重量`" v-if="[1, 2].includes(formData.type)">
            <ElInputNumber v-model="formData.targetWeight" class="w-32" :min="0" :max="80" :precision="2" />
            <div class="ml-2">KG</div>
          </ElFormItem>
          <ElFormItem>
            <ElButton type="primary" @click="formSubmit()">提交</ElButton>
            <ElButton @click="dialogInfo.vislble = false">取消</ElButton>
          </ElFormItem>
        </ElForm>
      </ElDialog>
      <div class="font-bold">任务状态</div>
      <div class="grid grid-cols-2 grid-rows-2 gap-2 text-sm whitespace-nowrap overflow-hidden">
        <div class="flex items-center gap-2">
          <div>执行车辆：</div>
          <ElTag>
            {{ getTaskCarName(Number(taskStatus.rid)) || '暂无任务' }}
          </ElTag>
        </div>
        <div class="flex items-center gap-2 place-self-end">
          <div>任务重量：</div>
          <ElTag> {{ Number(taskStatus.targetWeight || 0).toFixed(2) }} KG </ElTag>
        </div>
        <div class="flex items-center gap-2 col-span-2">
          <div>当前任务：</div>
          <ElTag class="text-ellipsis">
            {{ getTaskName(taskStatus.type) || '暂无任务' }}
          </ElTag>
        </div>
        <div class="flex items-center gap-2">
          <div>执行情况：</div>
          <ElTag :type="getTaskColor(taskStatus.status)">
            {{ getTaskStatus(taskStatus.status) || '暂无任务' }}
          </ElTag>
          <ElTag>{{ runningTime }}</ElTag>
        </div>
      </div>
      <ElScrollbar height="220" class="bg-#44648722 mt-1" always>
        <ElTimeline class="m-3 mb-0">
          <template v-for="item in timeLineItem" :key="item.time">
            <ElTimelineItem :timestamp="item.time" placement="top">
              {{ item.value }}
            </ElTimelineItem>
          </template>
        </ElTimeline>
      </ElScrollbar>
    </div>
  </div>
</template>
